package main

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strconv"
)

type Workspace struct {
	Name        string `json:"name"`
	IsDisplayed bool   `json:"isDisplayed"`
}

type Data struct {
	Workspaces []Workspace `json:"workspaces"`
}

type Root struct {
	Data Data `json:"data"`
}

func main() {
	if len(os.Args) < 2 {
		fmt.Println("miss arg")
		return
	}

	cmd := exec.Command("glazewm", "query", "workspaces")
	jsonString, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Println("exec command error:", err)
		return
	}

	command := os.Args[1]
	var root Root

	err = json.Unmarshal(jsonString, &root)
	if err != nil {
		fmt.Println("parse json data error:", err)
		return
	}

	for _, workspace := range root.Data.Workspaces {
		if workspace.IsDisplayed {
			executeCommand(command, workspace.Name)
			return
		}
	}
}

func executeCommand(command string, ws string) {
	int_ws, err := strconv.Atoi(ws)
	if err != nil {
		fmt.Println("change ws string to int error:", err)
		return
	}

	var target_ws string
	switch command {
	case "fr":
		target_ws = strconv.Itoa(int_ws + 1)
	case "fl":
		target_ws = strconv.Itoa(int_ws - 1)
	case "mr":
		target_ws = strconv.Itoa(int_ws + 1)
	case "ml":
		target_ws = strconv.Itoa(int_ws - 1)
	default:
		fmt.Println("unknow command:", command)
		return
	}

	cmd := exec.Command("glazewm", "command", "focus", "--workspace", target_ws)
	if command == "mr" || command == "ml" {
		cmd = exec.Command("glazewm", "command", "move", "--workspace", target_ws)
		cmd.CombinedOutput()
		cmd = exec.Command("glazewm", "command", "focus", "--workspace", target_ws)
	}
	cmd.CombinedOutput()
}
